// UDP通信工具类
import dgram from 'dgram';
const client = dgram.createSocket('udp4');
const server = dgram.createSocket('udp4');

const PORT = 3000; // 自定义端口号
const LOOPBACK_ADDRESS = '127.0.0.1';

// 客户端（消息发送方）
// client.send('Hello, myself!', 0, 'Hello, myself!'.length, PORT, LOOPBACK_ADDRESS, (err) => {
//     if (err) {
//         console.error(`Error sending message: ${err.stack}`);
//         client.close();
//     } else {
//         console.log('Message sent to loopback interface');
//         client.close(); // 发送后关闭套接字
//     }
// });

// 服务端（消息接受方）
// server.on('listening', () => {
//     const address = server.address();
//     console.log(`UDP server listening on ${address.address}:${address.port}`);
// });

// server.on('message', (message, remote) => {
//     console.log(`Received message: ${message} from ${remote.address}:${remote.port}`);
// });

// server.bind(PORT);

// 发送消息
export const sendMessage = () => {
    client.send('Hello, myself!', 0, 'Hello, myself!'.length, PORT, LOOPBACK_ADDRESS, (err) => {
        if (err) {
            console.error(`Error sending message: ${err.stack}`);
            // client.close();
        } else {
            console.log('Message sent to loopback interface');
            // client.close(); // 发送后关闭套接字
        }
    });
}

// 接受消息
export const receiveMessage = () => {

    server.bind(PORT);
    server.on('listening', () => {
        const address = server.address();
        console.log(`UDP server listening on ${address.address}:${address.port}`);
    });
    
    server.on('message', (message, remote) => {
        console.log(`Received message: ${message} from ${remote.address}:${remote.port}`);
    });

    // 发生异常时触发
    server.on('error', (err) => {
        console.log(`server error:${err.stack}`);
        server.close();
    });

    console.log("server")

}